package com.ebelter.btlibrary.btble.ble.bluetooth.device;


import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;

import com.ebelter.btlibrary.btble.ble.bluetooth.callback.BleSatusCallback;
import com.ebelter.btlibrary.btble.ble.bluetooth.callback.ConnectCallback;
import com.ebelter.btlibrary.btble.ble.bluetooth.callback.ScanResultCallback;
import com.ebelter.btlibrary.btble.ble.bluetooth.device.impl.BleMessageAnalyser;
import com.ebelter.btlibrary.btble.ble.bluetooth.device.impl.Channel;
import com.ebelter.btlibrary.btble.ble.model.BleDevice;
import com.ebelter.btlibrary.btble.ble.model.BleType;
import com.ebelter.btlibrary.btble.ble.model.BtAck;
import com.ebelter.btlibrary.btble.common.Fields;
import com.ebelter.btlibrary.btble.impl.scale.ScaleCommondEditor;
import com.ebelter.btlibrary.btble.impl.scale.ScaleMessageAnalyser;
import com.ebelter.btlibrary.btble.impl.scale.common.ScaleAck;
import com.ebelter.btlibrary.btble.impl.scale.common.ScaleBleConfigure;
import com.ebelter.btlibrary.btble.util.BytesUtils;
import com.ebelter.btlibrary.util.SpUtil;
import com.ebelter.btlibrary.util.ULog;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * 蓝牙数据传输服务
 */
@SuppressLint("NewApi")
public class BlueToothServer implements IBleServerWriter {
    private static String TAG = "BlueToothServer";        //tag
    protected Context mContext;                                    //context
    public boolean mScanning = false;                           //是否扫描
    private boolean isScanningRunning = false;                   //
    boolean isConnected = false;                        //是否已连接
    boolean isNeedConnecting = false;
    private int scanTimeout = BluetoothUtil.getScanTimeout();    //扫描超时时间
    int connectTotal = 0;

    static BluetoothAdapter mBluetoothAdapter;                //adapter
    int currDeviceType = -1;                        //当前测量设备类型
    BluetoothDevice currConnectDevice = null;        //当前连接设备
    int lastRssi = 0;                                //标记变量，用于记录上一次扫描到的设备的rssi信号
    BluetoothGatt mBluetoothGatt;
    long currMutualTime = 0;                        //当前数据交互时间
    //    protected AbstractDeviceDataHandle deviceDataHandler;    //数据处理
    String[] deviceReadNotifyUUIDs = null;        //蓝牙设备监听端口
    BluetoothGattService btService = null;
    private static BlueToothServer instance = null;
    int deviceConnectState = BluetoothProfile.STATE_DISCONNECTED;
    private boolean isListeneredBleState = false;

    Handler mHandler;
    MainHandle mMainHandler;
    private OnDeviceConnectedListener mConnectedListener;
    private BleSatusCallback mBleSatusCallback;
    ScanResultCallback mScanResultCallback;
    ConnectCallback mConnectCallback;//连接回调器
    BleMessageAnalyser mBleMessageAnalyser;


    private long lastDisconnectTime = 0;//上一次执行断开的时间
    private long lastconnectTime = 0;//上一次执行发现服务的时间
    private long clearGattTime = 0;//上一次执行清除Gstt的时间
    private static final int DISCONNECT_TIME_INTERVAL = 800;
    private static final int CONNECT_TIME_INTERVAL = 800;
    private static final int CLEAR_GATT_TIME_INTERVAL = 1000;

    //private boolean discoverServicesingFlag;


    private static final int DISCOVERSERVICES = 1;
    private static final int BLUETOOTH_ENABLE = 201;

//    public static boolean appRestartBlueToothing_Flag;//app内部重启的标志
//    private long appRestartBlueTooth_startTime;
//    private long appRestartBlueTooth_endTime;

    private static final int WHAT_GATT_RECONNECT = 33;//重连
    private static final int WHAT_CONNECTED = 34;//连接
    private static final int WHAT_DISCONNECTED = 35;//断开
    private static final int WHAT_CONNECTING = 36;//断开

    @SuppressLint("HandlerLeak")
    class MainHandle extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (msg.what == DISCOVERSERVICES) {
                removeDealRealseGatt();
                if (mBluetoothGatt != null) {
                    ULog.i(TAG, "------执行了发现服务");
                    mBluetoothGatt.discoverServices();
                }
            } else if (msg.what == BLUETOOTH_ENABLE) {
                ULog.e(TAG, "------BlueToothServer--手动开启了蓝牙");
                setBlueEnable(true);
                //appRestartBlueToothing_Flag=false;

            } else if (msg.what == WHAT_DISCONNECT_GATT_METHOD || msg.what == WHAT_DISCONNECT_GATT_QUANJU
                    || msg.what == WHAT_CLOSE_GATT_METHOD || msg.what == WHAT_CLOSE_GATT_QUANJU
                    || msg.what == WHAT_REFRESHDEVICECACHE_METHOD || msg.what == WHAT_REFRESHDEVICECACHE_QUANJU
                    || msg.what == WHAT_NO_CMD || msg.what == WHAT_REALSE_DISCONNECT_FINISH) {
               // dealRealseGatt(msg);
            } else if (msg.what == WHAT_CONNECTED) {
                ULog.i(TAG, "msg.what==WHAT_CONNECTED MainHandle执行了连接成功的回调");
                if (mConnectCallback != null) {
                    mConnectCallback.onConnected(currConnectDevice);
                }

            } else if (msg.what == WHAT_DISCONNECTED) {

                ULog.i(TAG, "msg.what==WHAT_DISCONNECTED MainHandle执行了断开连接的操作");
                clearBlueGatt();//清空
                if (mConnectCallback != null) {
                    mConnectCallback.onDisConnected();
                }
            } else if (msg.what == WHAT_CONNECTING) {
                ULog.i(TAG, "msg.what==WHAT_CONNECTING MainHandle接收到了正在连接的指令");
            }

        }
    }

    private void removeDealRealseGatt() {
        if (mMainHandler != null) {
            mMainHandler.removeMessages(WHAT_DISCONNECT_GATT_METHOD);
            mMainHandler.removeMessages(WHAT_DISCONNECT_GATT_QUANJU);
            mMainHandler.removeMessages(WHAT_CLOSE_GATT_METHOD);
            mMainHandler.removeMessages(WHAT_CLOSE_GATT_QUANJU);
            mMainHandler.removeMessages(WHAT_CLOSE_GATT_QUANJU);
            mMainHandler.removeMessages(WHAT_REFRESHDEVICECACHE_METHOD);
            mMainHandler.removeMessages(WHAT_REFRESHDEVICECACHE_QUANJU);
            mMainHandler.removeMessages(WHAT_REALSE_DISCONNECT_FINISH);
            ULog.i(TAG, "removeDealRealseGatt all what 把lastRealseDisconnectIng_Flag置为了false");
            lastRealseDisconnectIng_Flag = false;
        }
    }

    private void dealRealseGatt(Message msg) {

        // //第一步 先Disconnect掉方法里面的gatt
        // //第二步 先Close掉方法里面的gatt
        // //第三步 先释放掉方法里面的gatt
        // //第四步 先Disconnect掉全局里面的gatt
        // //第五步 先Close掉全局里面的gatt
        // //第六步 先释放掉全局里面的gatt
        // //第七步 最终完成

        if (msg.what == WHAT_REALSE_DISCONNECT_FINISH) {
            ULog.i(TAG, "关闭蓝牙 最终完成 把lastRealseDisconnectIng_Flag置为了false");

            lastRealseDisconnectIng_Flag = false;
        } else if (msg.what == WHAT_DISCONNECT_GATT_METHOD) {
            lastRealseDisconnectIng_Flag = true;
            BluetoothGatt gatt = (BluetoothGatt) msg.obj;
            int nextCmd = msg.arg1;
            ULog.i(TAG, "关闭蓝牙 执行了--方法中的gatt断开连接--methodGatt.disconnect())---nextCmd = " + nextCmd);
            if (gatt != null) {
                gatt.disconnect();
            }
            sendMsg2MainHandler(WHAT_CLOSE_GATT_METHOD, CLOSE_GATT_DEDAYED_small, gatt, WHAT_REFRESHDEVICECACHE_METHOD);

        } else if (msg.what == WHAT_CLOSE_GATT_METHOD) {
            lastRealseDisconnectIng_Flag = true;
            BluetoothGatt gatt = (BluetoothGatt) msg.obj;
            int nextCmd = msg.arg1;
            ULog.i(TAG, "关闭蓝牙 执行了--方法中的gatt-Close方法--methodGatt.close())---nextCmd = " + nextCmd);
            if (gatt != null) {
                gatt.close();
            }
            sendMsg2MainHandler(WHAT_DISCONNECT_GATT_QUANJU, CLOSE_GATT_DEDAYED_small, gatt, WHAT_CLOSE_GATT_QUANJU);
        } else if (msg.what == WHAT_REFRESHDEVICECACHE_METHOD) {
            lastRealseDisconnectIng_Flag = true;
            BluetoothGatt gatt = (BluetoothGatt) msg.obj;
            int nextCmd = msg.arg1;
            ULog.i(TAG, "关闭蓝牙 执行了--方法中的gatt释放缓存方法--refreshDeviceCache(methodGatt))--");
            //refreshDeviceCache(gatt);
            gatt = null;
            sendMsg2MainHandler(WHAT_DISCONNECT_GATT_QUANJU, CLOSE_GATT_DEDAYED_small, null, WHAT_CLOSE_GATT_QUANJU);
        } else if (msg.what == WHAT_DISCONNECT_GATT_QUANJU) {
            lastRealseDisconnectIng_Flag = true;
            ULog.i(TAG, "关闭蓝牙 执行了--全局的gatt断开连接--methodGatt.disconnect())---");
            if (mBluetoothGatt != null) {
                mBluetoothGatt.disconnect();
            }
            sendMsg2MainHandler(WHAT_CLOSE_GATT_QUANJU, CLOSE_GATT_DEDAYED_large, mBluetoothGatt, WHAT_REFRESHDEVICECACHE_QUANJU);

        } else if (msg.what == WHAT_CLOSE_GATT_QUANJU) {
            lastRealseDisconnectIng_Flag = true;
            BluetoothGatt gatt = (BluetoothGatt) msg.obj;
            int nextCmd = msg.arg1;
            ULog.i(TAG, "关闭蓝牙 执行了--全局的gatt-Close方法--methodGatt.close())---nextCmd = " + nextCmd);
            if (gatt != null) {
                gatt.close();
                mBluetoothGatt = null;
                btService = null;
            }
            sendMsg2MainHandler(WHAT_REFRESHDEVICECACHE_QUANJU, CLOSE_GATT_DEDAYED_large, gatt, WHAT_REALSE_DISCONNECT_FINISH);
        } else if (msg.what == WHAT_REFRESHDEVICECACHE_QUANJU) {
            lastRealseDisconnectIng_Flag = true;
            BluetoothGatt gatt = (BluetoothGatt) msg.obj;
            int nextCmd = msg.arg1;
            ULog.i(TAG, "关闭蓝牙 执行了--全局的gatt释放缓存方法--refreshDeviceCache(mBluetoothGatt))---nextCmd = " + nextCmd);
            // refreshDeviceCache(gatt);
            gatt = null;
            mBluetoothGatt = null;
            btService = null;
            sendMsg2MainHandler(WHAT_REALSE_DISCONNECT_FINISH, CLOSE_GATT_DEDAYED_large, null, WHAT_NO_CMD);
        }


    }


    public static final int CLOSE_GATT_DEDAYED_large = 1000;
    public static final int CLOSE_GATT_DEDAYED_small = 500;

    public static final int WHAT_NO_CMD = 66;

    public static final int WHAT_DISCONNECT_GATT_QUANJU = 70;
    public static final int WHAT_DISCONNECT_GATT_METHOD = 67;

    public static final int WHAT_CLOSE_GATT_QUANJU = 71;
    public static final int WHAT_CLOSE_GATT_METHOD = 68;

    public static final int WHAT_REFRESHDEVICECACHE_QUANJU = 72;
    public static final int WHAT_REFRESHDEVICECACHE_METHOD = 69;

    public static final int WHAT_REALSE_DISCONNECT_FINISH = 73;


    private long lastDealBluetoothGattTime;

    private void startDealBluetoothGatt(BluetoothGatt methodGatt, BluetoothGatt quanjuGatt) {

        if (lastRealseDisconnectIng_Flag) {
            ULog.i(TAG, "lastRealseDisconnectIng_Flag = true 上一次的释放未完成 此次 return");
            return;
        }
//        long tl=System.currentTimeMillis()-lastDealBluetoothGattTime;
//        if (tl<10000){
//            ULog.i(TAG,"距离上一次清除gatt未超过10秒 此次 return");
//            return;
//        }
        lastRealseDisconnectIng_Flag = true;
        lastDealBluetoothGattTime = System.currentTimeMillis();
        btService = null;


        // //第一步 先Disconnect掉方法里面的gatt
        // //第二步 先Close掉方法里面的gatt
        // //第三步 先释放掉方法里面的gatt
        // //第四步 先Disconnect掉全局里面的gatt
        // //第五步 先Close掉全局里面的gatt
        // //第六步 先释放掉全局里面的gatt
        // //第七步 最终完成

        if (methodGatt == null && quanjuGatt == null) {
            if (mMainHandler != null) mMainHandler.sendEmptyMessage(WHAT_REALSE_DISCONNECT_FINISH);
            return;
        }

        //延迟1s去Disconnect
        if (Objects.equals(methodGatt, quanjuGatt)) {
            //说明方法中的gatt和全局中的gatt是同一个对象
            ULog.i(TAG, "关闭蓝牙 执行了第一步 方法中的gatt和全局中的gatt --是-- 同一个对象");
            sendMsg2MainHandler(WHAT_DISCONNECT_GATT_QUANJU, CLOSE_GATT_DEDAYED_large, quanjuGatt, WHAT_CLOSE_GATT_QUANJU);
        } else {
            //说明方法中的gatt和全局中的gatt不是同一个对象
            ULog.i(TAG, "关闭蓝牙 执行了第一步 方法中的gatt和全局中的gatt --不是-- 不是同一个对象");
            sendMsg2MainHandler(WHAT_DISCONNECT_GATT_METHOD, CLOSE_GATT_DEDAYED_large, methodGatt, WHAT_DISCONNECT_GATT_QUANJU);
        }

    }

    private void sendMsg2MainHandler(int what, long delayed, Object obj, int nextCmd) {
        Message msg = Message.obtain();
        msg.what = what;
        msg.arg1 = nextCmd;
        msg.obj = obj;
        if (mMainHandler != null) mMainHandler.sendMessageDelayed(msg, delayed);
    }

    //sendfront是否要发送给前端的意思
    void clearBlueGatt() {
//        ULog.i(TAG, "gattConnect2Disconnect------------clearBlueGatt");
//        try {
//            if (mBluetoothGatt != null) {
//
//                mBluetoothGatt.disconnect();
//                mBluetoothGatt.close();
//                mBluetoothGatt = null;
//                btService = null;
//                currConnectDevice=null;
//                mBluetoothGattCallback=null;
//                isConnected = false;
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }


    //设置蓝牙开关
    private void setBlueEnable(boolean enable) {
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        if (adapter != null) {
            if (enable) {
                adapter.enable();
            } else {
                adapter.disable();
            }
        }
    }

    BlueToothServer(Context ctx) {
        this.mContext = ctx;

        mMainHandler = new MainHandle();

        HandlerThread handlerThread = new HandlerThread(TAG);
        handlerThread.start();
        mHandler = new Handler(handlerThread.getLooper());
    }

    @SuppressLint("HardwareIds")
    public static BlueToothServer getInstance(Context ctx) {
        if (instance == null) {

            BluetoothUtil.ConnectType mConnectType = BluetoothUtil.getConnectType();
            switch (mConnectType) {
                case GATT_AUTO_FALSE:
                    ULog.i(TAG, "getInstance()--mConnectType是---GATT_AUTO_FALSE--BlueToothServer");
                    instance = new BlueToothServer(ctx);
                    break;
                default:
                    ULog.i(TAG, "getInstance()--mConnectType是---default--BlueToothServer");
                    instance = new BlueToothServer(ctx);
                    break;
            }

            OnDeviceBindFoundListener.mac = SpUtil.readString(Fields.DEVICE_MAC, null);

            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

            instance.setListenerBluetoothState(true);
        }
        return instance;
    }

    public void registerScanResultCallback(ScanResultCallback callback) {
        this.mScanResultCallback = callback;
    }

    public void registerConnectCallback(ConnectCallback callback) {
        this.mConnectCallback = callback;
    }

    public void registerBleMessageAnalyser(BleMessageAnalyser messageAnalyser) {
        this.mBleMessageAnalyser = messageAnalyser;
    }


    /**
     * 开始扫描蓝牙设备
     */
    public void startScanDevice() {
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            ULog.e(TAG, "startScanDevice error. bluetoothAdapter not enabled.");
            return;
        }

        ULog.i(TAG, "startScanDevice. isScanningRunning:" + isScanningRunning);

        // 检查当前手机是否支持ble 蓝牙,如果不支持退出程序
        if (!isScanningRunning) {
            if (deviceConnectState == BluetoothProfile.STATE_DISCONNECTED) {
                isScanningRunning = true;
                if (mHandler != null) {
                    mHandler.removeCallbacks(scanningThread);
                    mHandler.post(scanningThread);
                }
            } else {
                ULog.e(TAG, "is already connected devices.don't do scan operate.");
            }
        } else {
            ULog.e(TAG, "is already scan devices.don't scan again.");
        }

    }

    /**
     * 停止扫描蓝牙设备
     */
    public void stopScanDevice() {
        ULog.i(TAG, "----stopScanDevice-----do stop scan device.");
        isScanningRunning = false;
        scanLeDevice(false);
        if (mHandler != null) {
            mHandler.removeCallbacks(scanningThread);
            //  mHandler.removeCallbacksAndMessages(null);
        }
    }


    private boolean lastRealseDisconnectIng_Flag = false;//释放连接ing标志

    /**
     * 开始连接设备
     */
    public void startConnectDevice(BluetoothDevice device) {
        if (device == null) return;

//        if (lastRealseDisconnectIng_Flag) {
//            ULog.i(TAG, "正在释放 lastRealseDisconnecFinish_Flag = ture 等待释放完全再连接 此次return");
//            return;
//        }


        ULog.i(TAG, "device地址是"+device+"---执行startConnectDevice isConnected:" + isConnected);

        if (!isConnected) {

            if (currConnectDevice==null){
                ULog.i(TAG, "A currConnectDevice为空 执行了发现服务");
                currConnectDevice = device;
                mBluetoothGatt = currConnectDevice.connectGatt(mContext, false, getGattCallBack());
                return;
            }

            if (TextUtils.equals(currConnectDevice.getAddress(),device.getAddress())){
                //连接的地址是一样的
                if (mBluetoothGatt!=null){
                    ULog.i(TAG, "A蓝牙地址 一样 mBluetoothGatt不为空 执行了connect()");
                    mBluetoothGatt.connect();
                }else {
                    ULog.i(TAG, "A蓝牙地址 一样 mBluetoothGatt为空 ");
                    mBluetoothGatt = currConnectDevice.connectGatt(mContext, false, getGattCallBack());
                }
            }else {
                //连接的地址是不一样的
                ULog.i(TAG, "A蓝牙地址 不一样 需重新连接");
                disConnectDevice();
                currConnectDevice = device;
                mBluetoothGatt=null;
                mBluetoothGatt = currConnectDevice.connectGatt(mContext, false, getGattCallBack());
            }



        } else {
            ULog.i(TAG, "说明已经连接成功");
            if (currConnectDevice != null) {
                if (TextUtils.equals(device.getAddress(), currConnectDevice.getAddress())) {
                    ULog.i(TAG, "B蓝牙地址 一样 无需重新连接");
                } else {
                    ULog.i(TAG, "B蓝牙地址 不一样 需重新连接");
                    disConnectDevice();
                    currConnectDevice = device;
                    mBluetoothGatt = currConnectDevice.connectGatt(mContext, false, getGattCallBack());
                }
            }
        }
    }

    public void startConnectDevice(String deviceAddress) {
        ULog.i(TAG, TAG + "--startConnectDevice()--deviceAddress = " + deviceAddress);
        try {
            BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(deviceAddress);
            startConnectDevice(device);
        } catch (Exception e) {
            e.printStackTrace();
            ULog.i(TAG, TAG + "---出现异常---startConnectDevice()--deviceAddress = " + deviceAddress);
        }

    }


    /**
     * 断开蓝牙连接
     */
    private void disConnectDevice() {

        stopScanDevice();

        isNeedConnecting = false;
        isConnected = false;
        connectTotal = 0;

        deviceConnectState = BluetoothProfile.STATE_DISCONNECTED;
        if (mBluetoothGatt != null) {
            ULog.i(TAG, "-----disConnectDevice--------mBluetoothGatt.disconnect()");
            mBluetoothGatt.disconnect();

           // mBluetoothGatt.close();
          //  refreshDeviceCache(mBluetoothGatt);
          //  mBluetoothGatt = null;

        }
       // btService=null;
//        if (mBluetoothGatt != null) {
//            startDealBluetoothGatt(null, mBluetoothGatt);
//        }


        // discoverServicesingFlag=false;

        if (mConnectCallback != null) {
            mConnectCallback.onDisConnected();
        }
        //currConnectDevice = null;

    }

//    private void clearGatt(BluetoothGatt gatt) {
//
//        if (gatt != null) {
//            ULog.i(TAG, "-------clearGatt--------gatt! = null");
//            if (System.currentTimeMillis() - clearGattTime > CLEAR_GATT_TIME_INTERVAL) {
//                ULog.i(TAG, "-------clearGatt--------执行成功");
//                gatt.disconnect();
//                gatt.close();
//                // refreshDeviceCache(gatt);
//                gatt = null;
//                btService = null;
//                currConnectDevice=null;
//                clearGattTime = System.currentTimeMillis();
//            }
//
//        }
//
//
//    }

    /**
     * 解绑设备
     */
    public void unbindDevice() {
        disConnectDevice();
        //解绑蓝牙设备
        OnDeviceBindFoundListener.mac = null;
    }

    //扫描设备
    protected void scanLeDevice(boolean enable) {

        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            ULog.e(TAG, "mBluetoothAdapter is null, or mBluetoothAdapter is not ebabled.");
            return;
        }
        ULog.i(TAG, "------scanLeDevice--------- enable = " + enable);
        if (enable) {
            ULog.d(TAG, "begin to scan bluetooth devices...");
            mScanning = true;
            try {
                mBluetoothAdapter.startLeScan(mLeScanCallback);
            } catch (Exception e) {
                ULog.e(TAG, "startLeScan error." + e.getMessage());
            }
        } else {
            ULog.d(TAG, "stop to scan bluetooth devices.");
            mScanning = false;
            try {
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
            } catch (Exception e) {
                ULog.e(TAG, "stopLeScan error." + e.getMessage());
            }
        }
    }


    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
        private long lastScanTime = 0;
        private String lastDeviceMac = "";

        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            if (device == null) return;

            ULog.i(TAG, "--------------onLeScan---------------name = " + device.getName() + ",address = " + device.getAddress() + " rssi=" + rssi);

            String name = device.getName();

            currDeviceType = BluetoothUtil.getDeviceTypeByDeviceName(name);
            ULog.i(TAG, "--------------onLeScan---------------name = " + device.getName() + ", currDeviceType = " + currDeviceType);
            if (currDeviceType > -1) {
                //TODO，停止继续扫描设备，该操作应该在匹配app绑定的mac地址后停止扫描
                //stopScanDevice();
                //只有未连接的时候才继续
                if (deviceConnectState != BluetoothProfile.STATE_DISCONNECTED) {
                    ULog.e(TAG, "deviceConnectState is：" + deviceConnectState);
                    return;
                }

                if (lastDeviceMac.equals(name)
                        && System.currentTimeMillis() - lastScanTime < 1000) {
                    ULog.i(TAG, "scan same device. address:" + lastDeviceMac);
                    lastDeviceMac = device.getAddress();
                    lastScanTime = System.currentTimeMillis();
                    return;
                }

                lastDeviceMac = device.getAddress();
                lastScanTime = System.currentTimeMillis();
                //这里首先校验当前扫描到的设备信号强度是否大于已经扫描到的设备信号强度
                lastRssi = rssi;
                //currConnectDevice = device;
                ULog.i(TAG, "found target device!");
                //通知发现设备
                if (mScanResultCallback != null) {
                    mScanResultCallback.onDiscovered(device);
                }
            }
        }
    };

//    private void monitor_fei0fei2(){
//        //TextUtils.equals(ScaleMessageAnalyser.getInstance().connectedBlueName, ScaleBleConfigure.BLE_NAME2)
//        if (blueStateChangeCount_fei0fei2>blueStateChangeCount_fei0fei2_max){
//            ULog.i(TAG,"blueStateChangeCount_fei0fei2 的数字超过了最大值 准备关闭蓝牙 3秒后重新开启");
//            setBlueEnable(false);
//            //blueStateChangeCount_fei0fei2=0;
//            if(mMainHandler!=null){
//                mMainHandler.sendEmptyMessageDelayed(BLUETOOTH_ENABLE,3000);
//            }
//        }
//    }


    //private int blueStateChangeCount_fei0fei2;//蓝牙状态非0非2的出现数字
    private static final int blueStateChangeCount_fei0fei2_max = 10;//蓝牙状态非0非2的出现数字
//

    private BluetoothGattCallback mBluetoothGattCallback;
    private BluetoothGattCallback getGattCallBack(){
        //连接回调信息
        if (mBluetoothGattCallback==null){
            mBluetoothGattCallback = new BluetoothGattCallback() {
                @Override
                public void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) {
                    ULog.i(TAG, "---onConnectionStateChange, status:" + status + ",new status:" + newState);//0 2 表示连接成功
                    if (status == BluetoothGatt.GATT_SUCCESS) {
                        if (newState == BluetoothProfile.STATE_CONNECTED) {
                            if (gatt != null) {
                                boolean success = gatt.discoverServices();
                                sendMessage(WHAT_CONNECTING, currConnectDevice);
                                ULog.i(TAG, "---onConnectionStateChange, ----> gatt.discoverServices() success = " + success);
                            }

                        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {

                            if (System.currentTimeMillis() - lastDisconnectTime > DISCONNECT_TIME_INTERVAL) {
                                lastDisconnectTime = System.currentTimeMillis();
                                ULog.i(TAG, "---onConnectionStateChange,newState == BluetoothProfile.STATE_DISCONNECTED");
                                sendEmptyMessage(WHAT_DISCONNECTED, 0);//回调给前端
                                isConnected = false;
                            }


                        }

                    } else {
                        //回调给前端接口
                        if (System.currentTimeMillis() - lastDisconnectTime > DISCONNECT_TIME_INTERVAL) {
                            lastDisconnectTime = System.currentTimeMillis();
                            sendEmptyMessage(WHAT_DISCONNECTED, 0);//回调给前端
                            ULog.i(TAG, "---onConnectionStateChange,status != BluetoothGatt.GATT_SUCCESS");
                            isConnected = false;
                        }
                    }

//            if (mMainHandler!=null){
//                mMainHandler.post(new Runnable() {
//                    @Override
//                    public void run() {
//
//                        ULog.w(TAG, "----onConnectionStateChange--------0 2 表示连接成功-------status = " + status + ",new status:" + newState);
//                        deviceConnectState = newState;
//                        //BluetoothGatt.GATT_SUCCESS = 0
//                        //BluetoothProfile.STATE_CONNECTED = 2
//                        if (status == BluetoothGatt.GATT_SUCCESS) {
//                            if (newState == BluetoothProfile.STATE_CONNECTED) {
//                                if (mMainHandler!=null&&System.currentTimeMillis()-lastconnectTime>CONNECT_TIME_INTERVAL){
//                                    lastconnectTime=System.currentTimeMillis();
//                                    mMainHandler.sendEmptyMessageDelayed(DISCOVERSERVICES,0);
//                                }
//                            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
//                                ULog.e(TAG, "newState 不是2. 准备关闭蓝牙连接操作 newState = "+newState);
//
//                                if (System.currentTimeMillis()-lastDisconnectTime>DISCONNECT_TIME_INTERVAL){
//                                    lastDisconnectTime=System.currentTimeMillis();
//                                    //blueStateChangeCount_fei0fei2++;
//                                   // monitor_fei0fei2();
//                                    //ULog.i(TAG,"status=0 但是 newState!=2 blueStateChangeCount_fei0fei2++ blueStateChangeCount_fei0fei2 = "+blueStateChangeCount_fei0fei2);
//                                    if (mConnectCallback != null) {
//                                        ULog.e(TAG, "newState 不是2. 准备关闭蓝牙连接操作--执行成功");
////                                        if (mBluetoothGatt!=null){
////                                            mBluetoothGatt.disconnect();
////                                            mBluetoothGatt.close();
////                                            refreshDeviceCache(mBluetoothGatt);
////                                            mBluetoothGatt=null;
////                                            btService=null;
////                                        }
//                                        startDealBluetoothGatt(gatt,mBluetoothGatt);
//                                        isConnected = false;
//                                        mConnectCallback.onDisConnected();
//
//                                    }
//                                }
//                            }
//                        } else {
//                            ULog.e(TAG, "status 不是0. 准备关闭蓝牙连接操作 status="+status);
//                            if (System.currentTimeMillis()-lastDisconnectTime > DISCONNECT_TIME_INTERVAL) {
//                                lastDisconnectTime = System.currentTimeMillis();
//                               // blueStateChangeCount_fei0fei2++;
//                               // monitor_fei0fei2();
//                               // ULog.i(TAG,"status!=0 blueStateChangeCount_fei0fei2++ blueStateChangeCount_fei0fei2 = "+blueStateChangeCount_fei0fei2);
//                                if (mBluetoothGatt != null) {
//                                    ULog.e(TAG, "status 不是0. 准备关闭蓝牙连接操作--执行成功");
////                                    mBluetoothGatt.disconnect();
////                                    mBluetoothGatt.close();
////                                    refreshDeviceCache(mBluetoothGatt);
////                                    mBluetoothGatt = null;
////                                    btService = null;
//                                    startDealBluetoothGatt(gatt,mBluetoothGatt);
//                                }
//                                if (mConnectCallback != null) {
//                                    isConnected = false;
//                                    mConnectCallback.onDisConnected();
//                                }
//
//                                if (status==257){
//                                    ULog.e(TAG,"----蓝牙状态进入了status = 257状态");
//                                }
//                            }
//                        }
//
//                    }
//                });
//            }


                }


                @Override
                public void onServicesDiscovered(final BluetoothGatt gatt, int status) {
                    ULog.w(TAG, "--------------onServicesDiscovered---------------status = " + status);
                    if (status == BluetoothGatt.GATT_SUCCESS) {

                        //搜寻设备完毕，写入数据特征到设备中
                        if (mBluetoothAdapter == null) {
                            ULog.e(TAG, "BluetoothAdapter not initialized");
                            return;
                        }

                        //打印出当前设备的services列表
                        List<BluetoothGattService> gattServices = gatt.getServices();
                        for (BluetoothGattService service : gattServices) {
                            ULog.i(TAG, "-----onServicesDiscovered-------service uuid:" + service.getUuid().toString());
                        }

                        btService = gatt.getService(UUID.fromString(BluetoothUtil.getDeviceServiceUUID()));
                        if (btService == null) {
                            ULog.e(TAG, "找 不到 对应的服务");
                            //状态码出错，先断开连接然后再重新连接
                            isConnected = false;
                            return;
                        }

                        ULog.e(TAG, "找 到 了对应的服务");

                        List<BluetoothGattCharacteristic> characteristics = btService.getCharacteristics();
                        for (BluetoothGattCharacteristic characteristic : characteristics) {
                            ULog.i(TAG, "-----onServicesDiscovered-------characteristic uuid:" + characteristic.getUuid().toString());
                            setCharacteristicNotification(characteristic);
                        }
                        //数据通知uuid列表
                        deviceReadNotifyUUIDs = BluetoothUtil.getReadUUIDs();

                        BluetoothGattCharacteristic characteristic = btService.getCharacteristic(UUID.fromString(deviceReadNotifyUUIDs[0]));
                        if (characteristic != null) {
                            setCharacteristicNotification(characteristic);

                        }


                    } else {
                        ULog.w(TAG, "onServicesDiscovered received: " + status);
                        isConnected = false;
                        sendEmptyMessage(WHAT_DISCONNECTED, 0);
                    }
                }


                public void onDescriptorWrite(final BluetoothGatt gatt, BluetoothGattDescriptor gattDescriptor, int status) {
                    ULog.w(TAG, "--------------onDescriptorWrite---------------status = " + status);
                    if (status != 0) {
                        ULog.i(TAG, "onDescriptorWrite, status not 0, do disconnect.");
                        sendEmptyMessage(WHAT_DISCONNECTED, 0);
                    } else {

                        connectTotal++;
                        ULog.i(TAG, "device connected times." + connectTotal
                                + ",isConnected:" + isConnected);

                        UUID uuid = gattDescriptor.getCharacteristic().getUuid();
                        ULog.i(TAG, "-----onDescriptorWrite------UUID = " + uuid + ", deviceReadNotifyUUIDs.length = " + deviceReadNotifyUUIDs.length);

                        //设置多通道通知
                        setMutiNotify(uuid, 1);
                        setMutiNotify(uuid, 2);
                        setMutiNotify(uuid, 3);

                        isConnected = true;
                        sendMessage(WHAT_CONNECTED, currConnectDevice);


                    }

                }


                @Override
                public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
                    //读取到数据
                    ULog.w(TAG, "--------------onCharacteristicRead---------------status = " + status);
                }

                /**
                 * 返回数据。
                 */
                @Override
                public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
                    currMutualTime = System.currentTimeMillis();

                    ULog.i(TAG, "----onCharacteristicChanged---characteristic UUID :" + characteristic.getUuid().toString() + "\n, value = " + BytesUtils.bytes2HexStr(characteristic.getValue()));


                    byte[] value = characteristic.getValue();
                    if (value != null) {
                        onReceiveBleMessage(characteristic.getUuid().toString(), value);//2
                    }
                }
            };
        }

        return mBluetoothGattCallback;
    }



    private void setMutiNotify(UUID uuid, int channelNumber) {
        if (deviceReadNotifyUUIDs.length > channelNumber) {
            if (uuid.toString().equals(deviceReadNotifyUUIDs[channelNumber - 1])) {
                ULog.i(TAG, "-----onDescriptorWrite---characteristic " + (channelNumber - 1) + "----set notifty characteristic " + channelNumber);
                BluetoothGattCharacteristic characteristic = btService.getCharacteristic(UUID.fromString(deviceReadNotifyUUIDs[channelNumber]));
                if (characteristic != null) {
                    setCharacteristicNotification(characteristic);
                }
            }
        }
    }


    private void setCharacteristicNotification(BluetoothGattCharacteristic characteristic) {
        if (mBluetoothGatt != null) {
            mBluetoothGatt.setCharacteristicNotification(characteristic, true);
            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(BluetoothUtil.CLIENT_CHARACTERISTIC_CONFIG));
            if (descriptor != null) {
                ULog.i(TAG, "mBluetoothGatt.writeDescriptor.");
                descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                mBluetoothGatt.writeDescriptor(descriptor);
            }
        }

    }

    // private StringBuilder dataSb;

    private void onReceiveBleMessage(String uuid, byte[] value) {
//        // 数据
//        if (dataSb == null) {
//            dataSb = new StringBuilder();
//        } else {
//            dataSb.setLength(0);
//        }
//
//        for (byte aValue : value) {
//            dataSb.append(Integer.toHexString(aValue & 0xff));
//            dataSb.append(" ");
//        }
//        ULog.i(TAG, "receive device data:" + dataSb.toString());

        Channel mChannel = null;
        if (uuid.equals(deviceReadNotifyUUIDs[0])) {
            mChannel = Channel.CHANNEL_0;
        } else if (deviceReadNotifyUUIDs.length > 1 && uuid.equals(deviceReadNotifyUUIDs[1])) {
            mChannel = Channel.CHANNEL_1;
        } else if (deviceReadNotifyUUIDs.length > 2 && uuid.equals(deviceReadNotifyUUIDs[2])) {
            mChannel = Channel.CHANNEL_2;
        } else if (deviceReadNotifyUUIDs.length > 3 && uuid.equals(deviceReadNotifyUUIDs[3])) {
            mChannel = Channel.CHANNEL_3;
        } else if (deviceReadNotifyUUIDs.length > 4 && uuid.equals(deviceReadNotifyUUIDs[4])) {
            mChannel = Channel.CHANNEL_4;
        } else if (deviceReadNotifyUUIDs.length > 5 && uuid.equals(deviceReadNotifyUUIDs[5])) {
            mChannel = Channel.CHANNEL_5;
        } else if (deviceReadNotifyUUIDs.length > 6 && uuid.equals(deviceReadNotifyUUIDs[6])) {
            mChannel = Channel.CHANNEL_6;
        } else if (deviceReadNotifyUUIDs.length > 7 && uuid.equals(deviceReadNotifyUUIDs[7])) {
            mChannel = Channel.CHANNEL_7;
        }

        if (mBleMessageAnalyser != null && mChannel != null) {
            mBleMessageAnalyser.onReceiveBleMessage(mChannel, value);//1
        }
    }


    private void sendMessage(int what, Object object) {
        if (mMainHandler != null) {
            Message message = mMainHandler.obtainMessage();
            message.what = what;
            message.obj = object;
            mMainHandler.sendMessage(message);
        }
    }

    private void sendEmptyMessage(int what, long delay) {
        if (mMainHandler != null) {
            mMainHandler.sendEmptyMessageDelayed(what, delay);
        }
    }

    // private final Object obj = new Object();


    /**
     * 写入数据到设备
     */
    @Override
    public void writeLlsAlertLevel(String desc, byte[] bb) {


        currMutualTime = System.currentTimeMillis();

        if (!isConnected) {
            ULog.e(TAG, "体脂秤未连接 此次不发送 return");
            return;
        }
        //BluetoothGattService linkLossService = mBluetoothGatt.getService(UUID.fromString(BluetoothUtil.getDeviceServiceUUID(currDeviceType)));
        if (btService == null) {
            ULog.e(TAG, "btService为null不能发送");
            return;
        }
        BluetoothGattCharacteristic alertLevel = btService.getCharacteristic(UUID.fromString(BluetoothUtil.getWriteUUID()));

        if (alertLevel == null) {
            ULog.e(TAG, "link loss Alert Level charateristic not found!");
            return;
        }

        if (mBluetoothGatt == null) {
            ULog.e(TAG, "mBluetoothGatt is null");
            return;
        }

        boolean status;
        int storedLevel = alertLevel.getWriteType();
        ULog.d(TAG, "storedLevel() - storedLevel=" + storedLevel);
        alertLevel.setValue(bb);
        alertLevel.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
        status = mBluetoothGatt.writeCharacteristic(alertLevel);
        ULog.i(TAG, "----发送的指令-- - 是否成功 = " + status + "--" + desc + ", bytes = " + BytesUtils.bytes2HexStr(bb));


//            private static final byte[] getHistoryDataACK= {(byte) 0xab, 0x02, (byte) 0x9b, 0x01};
//            private static final byte[] getMesureDataACK= {(byte) 0xab, 0x02, (byte) 0xa3, 0x00};


        if (status) {
            //说明发送成功
            ScaleCommondEditor.getInstance().sendDataTime = System.currentTimeMillis();
        }

    }

    //循环监听扫描状态
    private Runnable scanningThread = new Runnable() {
        public void run() {
            String threadName = Thread.currentThread().getName();
            ULog.i(TAG, "------scanningThread-----run---threadName = " + threadName);

            scanLeDevice(false);

            SystemClock.sleep(1000);

            scanLeDevice(true);
            if (mHandler != null) {   //zcq删除于201804031810
                mHandler.postDelayed(this, scanTimeout);
            }
        }
    };

    /**
     * 监听蓝牙 打开/关闭 状态
     */
    private void setListenerBluetoothState(boolean enable) {
        if (enable) {
            if (!isListeneredBleState) {
                isListeneredBleState = true;
                mContext.registerReceiver(mReceiver, makeBleStateFilter(), "android.permission.BIND_APPWIDGET", new Handler(Looper.myLooper()));
            }
        } else {
            if (isListeneredBleState) {
                isListeneredBleState = false;
                mContext.unregisterReceiver(mReceiver);
            }
        }
    }

    /**
     * 断开当前连接并且退出设备扫描
     */
    public void disConnectAndStopScan() {
        ULog.i(TAG, "------disConnectAndStopScan-----");

        disConnectDevice();
        //stopScanDevice();
    }

    /**
     * 延迟断开连接和关闭设备扫描
     */
    // private void delayDisconnectAndStopScan() {
    //停止心跳
//        ((WeightDataHandle) deviceDataHandler).stopConnHeartbeat();
    //   cancelBackgroundedNow();
//        if (mHandler != null) {
//            mHandler.removeCallbacks(dataMutualThread);
//            mHandler.post(dataMutualThread);
//        }
    // }


    /**
     * 监听数据通讯线程
     */
//    private Runnable dataMutualThread = new Runnable() {
//        public void run() {
//            ULog.i(TAG, "dataMutualThread." + Thread.currentThread().getName());
//            if (System.currentTimeMillis() - currMutualTime > BluetoothUtil.getNoMessageTimeout()) {
//                ULog.i(TAG, "do delayDisconnectAndStopScan");
//                setListenerBluetoothState(false);
//                disConnectAndStopScan();
//
//                //此处sleep 1秒给app断开释放连接资源使用
//                try {
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//
//                ULog.i(TAG, "do releaseDevice for huaweihealth sdk.");
//            } else {
//                if (mHandler != null) {
//                    mHandler.postDelayed(this, 500);
//                }
//            }
//        }
//    };


//    public void refreshDeviceCache() {
//        mBluetoothGatt.disconnect();
//        refreshDeviceCache(mBluetoothGatt);
//        mBluetoothGatt.close();
//    }


//    void refreshDeviceCache(final BluetoothGatt gatt) {
//        /*
//         * There is a refresh() method in BluetoothGatt class but for now it's hidden. We will call it using reflections.
//		 */
////		try {
////			final Method refresh = gatt.getClass().getMethod("refresh");
////			if (refresh != null) {
////				final boolean success = (Boolean) refresh.invoke(gatt);
////				ULog.i(TAG, "Refreshing result: " + success);
////			}
////		} catch (Exception e) {
////			ULog.e(TAG, "An exception occurred while refreshing device");
////		}
//    }

    /**
     * 蓝牙状态监听
     */
    private IntentFilter makeBleStateFilter() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        return filter;
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (Objects.equals(intent.getAction(), BluetoothAdapter.ACTION_STATE_CHANGED)) {
                int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);

                if (blueState == BluetoothAdapter.STATE_TURNING_ON) {
                    ULog.i("BLE state receiver", "STATE_TURNING_ON");

                    if (mBleSatusCallback != null) {
                        mBleSatusCallback.onBleTurningOn();
                    }
                } else if (blueState == BluetoothAdapter.STATE_ON) {
                    ULog.i("BLE state receiver", "STATE_ON");
                    if (mBleSatusCallback != null) {
                        mBleSatusCallback.onBleStateOn();
                    }
//                    deviceDataHandler.getMsgCallBack().onBluetoothOpened();
                    //   startScanDevice();
                } else if (blueState == BluetoothAdapter.STATE_TURNING_OFF) {
                    ULog.i("BLE state receiver", "STATE_TURNING_OFF");
                    if (mBleSatusCallback != null) {
                        mBleSatusCallback.onBleTurningOff();
                    }
                    stopScanDevice();
//                    deviceDataHandler.sendDisconnectBt();


                    if (mBluetoothGatt != null) {
                        mBluetoothGatt.disconnect();
                        //mBluetoothGatt.close();
                        //  refreshDeviceCache(mBluetoothGatt);
                       // mBluetoothGatt = null;
                       // btService = null;
                    }
                    isConnected = false;
                    mScanning = false;
                    deviceConnectState = BluetoothProfile.STATE_DISCONNECTED;
                } else if (blueState == BluetoothAdapter.STATE_OFF) {
                    ULog.i("BLE state receiver", "STATE_OFF");
                    if (mBleSatusCallback != null) {
                        mBleSatusCallback.onBleStateOff();
                    }
                    //UToast.ShowTask(mContext, "请打开手机蓝牙.");
                    stopScanDevice();
//                    deviceDataHandler.getMsgCallBack().onBluetoothClosed();
                }
            } else if (Objects.equals(intent.getAction(), BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {//蓝牙扫描结束
                ULog.i(TAG, "-----蓝牙扫描结束---");
            }
        }
    };


    //app退出到后台相关逻辑处理
//    public void delayBackgrounded() {
//        ULog.i(TAG, "delayBackgrounded.");
//        if (mHandler != null) {
//            mHandler.postDelayed(appBackgrounded, 3000);
//        }
//    }
//
//    public void cancelBackgrounded() {
//        ULog.i(TAG, "cancelBackgrounded.");
//        if (mHandler != null) {
//            mHandler.postDelayed(cancelAppBackgrounded, 2000);
//        }
//    }

//    private void cancelBackgroundedNow() {
//        ULog.i(TAG, "cancelBackgrounded now.");
//        if (mHandler != null) {
//            mHandler.removeCallbacks(appBackgrounded);
//        }
//    }

//    private Runnable appBackgrounded = new Runnable() {
//
//        @Override
//        public void run() {
//            if (!isForeground(mContext)) {
//                ULog.i(TAG, "appBackgrounded appBackgrounded.");
//                delayDisconnectAndStopScan();
//            } else {
//                ULog.i(TAG, "appBackgrounded cancel, app is Foreground.");
//            }
//        }
//    };
//
//    private Runnable cancelAppBackgrounded = new Runnable() {
//
//        @Override
//        public void run() {
//            ULog.i(TAG, "appBackgrounded cancelAppBackgrounded.");
//            if (mHandler != null) {
//                mHandler.removeCallbacks(appBackgrounded);
//            }
//        }
//    };


    //当前应用是否处于前台
    private boolean isForeground(Context context) {
        if (context != null) {
            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> rtInfos = null;
            if (am != null) {
                rtInfos = am.getRunningTasks(1);
            }
            if (rtInfos != null && !rtInfos.isEmpty()) {
                ComponentName cn = rtInfos.get(0).topActivity;
                String currentPackageName = cn.getPackageName();
                if (!TextUtils.isEmpty(currentPackageName) && currentPackageName.equals(context.getPackageName())) {
                    return true;
                }
            }
            return false;
        }
        return false;
    }

//    public void setOnDeviceConnectedListener(OnDeviceConnectedListener mConnectedListener) {
//        this.mConnectedListener = mConnectedListener;
//    }

//    OnDeviceBindFoundListener mDeviceBindFoundListener = new OnDeviceBindFoundListener() {
//        @Override
//        public void onDeviceBindFound(BluetoothDevice device) {
//            ULog.i(TAG, "----startScan----onDeviceBindFound----addr = " + device.getAddress());
//            startConnectDevice(device);
//        }
//    };

    public void setBleSatusCallback(BleSatusCallback mBleSatusCallback) {
        this.mBleSatusCallback = mBleSatusCallback;
    }

    /**
     * Clears the internal cache and forces a refresh of the services from the remote device.
     */
//    public static boolean refreshDeviceCache(BluetoothGatt mBluetoothGatt) {
//        if (mBluetoothGatt != null) {
//            try {
//                Method localMethod = mBluetoothGatt.getClass().getMethod("refresh", new Class[0]);
//                if (localMethod != null) {
//                    boolean bool = (Boolean) localMethod.invoke(mBluetoothGatt, new Object[0]);
//                    return bool;
//                }
//            } catch (Exception localException) {
//                Log.i(TAG, "An exception occured while refreshing device");
//            }
//        }
//        return false;
//    }

    protected StringBuffer sb;

    private synchronized String getArrayString(byte[] data) {
        if (sb == null) {
            sb = new StringBuffer();
        }
        sb.setLength(0);
        int i = 0;
        while (i < data.length) {
            sb.append(Integer.toHexString(data[i] & 0xff)).append(" ");
            i++;
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }

    /**
     * 释放资源的方法
     */
    public void release() {
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }

        mConnectedListener = null;
        mBleSatusCallback = null;
        mScanResultCallback = null;
        mConnectCallback = null;
        mBleMessageAnalyser = null;


        //断开链接,置空
        if (mBluetoothGatt != null) {
            mBluetoothGatt.disconnect();
            mBluetoothGatt.close();
            //  refreshDeviceCache(mBluetoothGatt);
            mBluetoothGatt = null;
            btService = null;
        }

        //释放资源
        if (mBluetoothAdapter != null) {
            mBluetoothAdapter = null;
        }

        instance = null;

    }

}